package com.fanshuai.spring.boot.controller;

import com.fanshuai.spring.boot.service.CacheService;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
public class CacheController {
    @Resource
    private CacheService cacheService;

    @PostMapping(value = "/string/set")
    public boolean set(@RequestParam(value = "key")  String key,
                       @RequestParam(value = "value") String value) {
        return cacheService.set(key, value);
    }

    @GetMapping("/string/get")
    public String get(@RequestParam(value = "key")  String key) {
        return cacheService.get(key);
    }

    @PostMapping("/zset/zadd")
    public boolean zadd(@RequestParam(value = "key")  String key,
                        @RequestParam(value = "value") String value,
                        @RequestParam(value = "score") double score) {
        cacheService.zadd(key, value, score);
        return true;
    }

    @GetMapping("/zset/zrange")
    public Set<String> zrange(@RequestParam(value = "key")  String key,
                              @RequestParam(value = "start") long start,
                              @RequestParam(value = "end") long end) {
        return cacheService.zrange(key, start, end);
    }

    @PostMapping("/publish")
    public boolean publish(String channel, String msg) {
        return cacheService.publish(channel, msg);
    }

    @PostMapping("/pipelined")
    public boolean setPipelined(String key1, String v1, String key2, String v2) {
        Map<String, String> map = ImmutableMap.of(key1, v1, key2, v2);
        cacheService.setPipelined(map);
        return true;
    }

    @PostMapping("/cas/lua")
    public boolean executeLua(String key, String curValue, String setValue) {
        String lua = "-- checkandset.lua\n" +
                "local current = redis.call('GET', KEYS[1])\n" +
                "if current == ARGV[1]\n" +
                "  then redis.call('SET', KEYS[1], ARGV[2])\n" +
                "  return true\n" +
                "end\n" +
                "return false";

        List<String> keys = ImmutableList.of(key);
        List<Object> args = ImmutableList.of(curValue, setValue);
        return cacheService.executeLua(lua, keys, args, Boolean.class);
    }
}
